<script setup lang="ts">
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { adminUploadDocumentService, adminUploadVideoService } from '@/api/admin'
import { useCountStore } from '@/stores/TeaStatisticsCount'

// 控制上传状态和进度
const uploadProgress = ref(0) // 上传进度
const formData = ref({
  title: '',
  remark: '',
  documentUrl: ''
})
const fileList = ref([]) // 已上传文件列表
const isUploading = ref(false) // 是否正在上传，控制进度条的显示

// 自定义上传处理
const beforeUpload = (file: File) => {
  // 允许上传的文件类型
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const isAllowedType = allowedTypes.some((type) => file.type.startsWith(type)) // 只允许上传指定类型
  if (!isAllowedType) {
    ElMessage.error('只能上传视频或文档文件（PDF, DOC, DOCX）')
    return false
  }

  const isLt200MB = file.size / 1024 / 1024 < 20 // 文件大小限制20MB
  if (!isLt200MB) {
    ElMessage.error('文档大小应不超过20MB')
    return false
  }
  isUploading.value = true // 开始上传时，显示进度条
  uploadProgress.value = 0 // 重置进度条为 0
  return true
}

// 处理文件上传
const handleUploadSuccess = (response: any, file: File) => {
  // 上传成功后，处理逻辑，比如保存文件的 URL 和其他信息
  ElMessage.success('上传成功')
  console.log(response)
  formData.value.documentUrl = response.data // 假设服务器返回的 response.data 是文件的 URL
  isUploading.value = false // 上传成功，隐藏进度条
  uploadProgress.value = 0 // 重置进度条
}

// 处理上传失败
const handleUploadError = (err: any, file: File) => {
  ElMessage.error('上传失败，请重试')
  console.error(err)
  isUploading.value = false // 上传失败，隐藏进度条
  uploadProgress.value = 0 // 重置进度条
}

// 上传进度处理
const handleProgress = (event: ProgressEvent, file: File) => {
  if (event.lengthComputable) {
    uploadProgress.value = Math.round((event.loaded / event.total) * 100)
  }
}

const publish = async () => {
  if (formData.value.title === '' || formData.value.documentUrl === '') {
    ElMessage.error('请填写标题和上传文件')
    return
  }
  await adminUploadDocumentService(formData.value)
  ElMessage.success('发布成功')
  formData.value.title = ''
  formData.value.documentUrl = ''
  formData.value.remark = ''
  await useCountStore().getContentCount()
}
</script>

<template>
  <div id="main-teaResourceDocumentCreatePage">
    <h1>上传文档</h1>
    <el-form style="margin-top: 10px">
      <el-form-item>
        <el-input v-model="formData.title" placeholder="标题名称" style="width: 50%" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="formData.remark" placeholder="备注（可选）" style="width: 50%" />
      </el-form-item>
    </el-form>

    <!-- 上传组件 -->
    <el-upload
      class="upload-demo"
      drag
      :action="'http://localhost:8000/teacher/common/upload'"
      :headers="{ authentication: useUserStore().token }"
      :file-list="fileList"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :limit="1"
      :auto-upload="true"
      :accept="'document/*,.pdf,.doc,.docx'"
    >
      <el-icon class="el-icon--upload">
        <UploadFilled />
      </el-icon>
      <div class="el-upload__text">将文件拖动于此 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">文件大小应不超过20MB（支持PDF、DOC、DOCX）</div>
      </template>
    </el-upload>

    <!-- 上传进度，仅在上传时显示 -->

    <el-button type="primary" @click="publish" style="margin-top: 20px">发布</el-button>
  </div>
</template>

<style scoped>
#main-teaResourceDocumentCreatePage {
  padding: 20px;
}

.el-upload__text {
  font-size: 16px;
}
</style>
